package com.kystar.ledcontrol.recycleview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;

import com.kystar.ledcontrol.recycleview.help.SaveBitmap;
import com.kystar.ledcontrol.recycleview.util.TDevice;
import com.kystar.ledcontrol.recycleview.util.TLog;

/**
 * Created by peanut on 2018/05/31.
 */

public class MyImageView extends android.support.v7.widget.AppCompatImageView implements ScaleGestureDetector.OnScaleGestureListener,
        ViewTreeObserver.OnGlobalLayoutListener {
    private static final String TAG = "MyImageView";
    public static final float SCALE_MAX = 4.0f;
    /**
     * 初始化时的缩放比例，如果图片宽或高大于屏幕，此值将小于0
     */
    private float initScale = 1.0f;

    /**
     * 用于存放矩阵的9个值
     */
    private final float[] matrixValues = new float[9];
    private boolean once = true;
    /**
     * 缩放的手势检测
     */
    private ScaleGestureDetector mScaleGestureDetector = null;
    private final Matrix mScaleMatrix = new Matrix();

    public MyImageView(Context context) {
        super(context);
        init(context);
    }

    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        super.setScaleType(ScaleType.FIT_XY);
        mScaleGestureDetector = new ScaleGestureDetector(context, this);
    }

    ViewPager viewPager;
    boolean isScaleSmall = false;
    boolean isScaleNormal = true;
    private static final int SCALESMALL = 0;
    private static final int SCALENORMAL = 1;
    private static final int SCALELARGE = 2;
    private int scaleState = -1;
    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        LinearLayout.LayoutParams layoutParams;
        float scale = getScale();
        float scaleFactor = detector.getScaleFactor();
        LinearLayout linearLayout = (LinearLayout) viewPager.getParent();
        Drawable d = getDrawable();

        if(scaleFactor < 1 && scaleState == SCALENORMAL&&isOnce ){
            setScaleType(ScaleType.FIT_XY);
            layoutParams = new LinearLayout.LayoutParams((int) (2*TDevice.getScreenWidth()/3),
                    (int) TDevice.getScreenHeight()/2);
            viewPager.setLayoutParams(layoutParams);
            float widthDraw = d.getIntrinsicWidth();
            float heightDraw = d.getIntrinsicHeight();
            TLog.e("widthDraw",widthDraw,"heightDraw",heightDraw);
            setPadding(50,0,50,0);
            linearLayout.setClipChildren(false);
            linearLayout.setBackgroundColor(Color.BLACK);
            scaleState = SCALESMALL;
        }

        if(scaleFactor>1 && scaleState == SCALESMALL&&isOnce){
          //  mScaleMatrix.setScale(1f,1f);
            layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            viewPager.setLayoutParams(layoutParams);
            setScaleType(ScaleType.FIT_XY);
            setPadding(0,0,0,0);
            linearLayout.setClipChildren(true);
          //  linearLayout.setBackgroundColor(Color.TRANSPARENT);
            scaleState = SCALENORMAL;
            isOnce = false;
        }

        if(scaleFactor > 1 && scaleState >=SCALENORMAL &&scale < 2 &&isOnce){
            Drawable drawable = getDrawable();
            if(drawable.getIntrinsicWidth() < TDevice.getScreenWidth()){
                //drawable.getIntrinsicWidth得到的是图片第一次被加载进来的时候的宽度与它的布局的大小有关，所以缩略图中的图片的大小是有四分之一
                //需要重新设置图片的内容，将drawable转化为bitmap，并在此过程中，将bitmap的宽高设置为屏幕的宽高
                Bitmap bitmap = SaveBitmap.drawableToBitmap(drawable,(int) TDevice.getScreenWidth(),(int) TDevice.getScreenHeight());
                setImageBitmap(bitmap);
                TLog.e("bitmap");
            }
            setScaleType(ScaleType.MATRIX);
            mScaleMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());
            setImageMatrix(mScaleMatrix);
            scaleState = SCALELARGE;
        }
        if(scaleFactor < 1 && scaleState == SCALELARGE){
            if(scale <= 1){
                mScaleMatrix.setScale(1f,1f);
                setScaleType(ScaleType.FIT_XY);
                scaleState = SCALENORMAL;
                TLog.e("scale = 1");
                isOnce = false;
                return true;
            }
            setScaleType(ScaleType.MATRIX);
            mScaleMatrix.postScale(scaleFactor,scaleFactor,detector.getFocusX(), detector.getFocusY());
            setImageMatrix(mScaleMatrix);
        }
        TLog.e("scale",scale);
        return true;
    }

    public final float getScale()
    {
        mScaleMatrix.getValues(matrixValues);
        return matrixValues[Matrix.MSCALE_X];
    }
    boolean isOnce = false;
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        isOnce = true;
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
        TLog.e(TAG,"onScaleEnd",scaleState);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mScaleGestureDetector.onTouchEvent(event);
    }

    @Override
    protected void onAttachedToWindow()
    {
        super.onAttachedToWindow();
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onDetachedFromWindow()
    {
        super.onDetachedFromWindow();
        getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {//在每一次布局改变时，都会被调用，在这个里面改变布局，可以解决viewpager的缓存问题
        int width = getWidth();
        int height = getHeight();
        viewPager = (ViewPager) getParent();
        if(width<=2*TDevice.getScreenWidth()/3){
            setPadding(50,0,50,0);//设置imageView本身的padding值使两个页面看上去间隔一段距离，无法使用setPagerMargin
            scaleState = SCALESMALL;
        }else if(width == TDevice.getScreenWidth()){
            setPadding(0,0,0,0);
            scaleState = SCALENORMAL;
        }
        TLog.e("onGlobal");

    }
}
